//
//  AppDelegate.swift
//  MySinaWeibo
//
//  Created by apple on 15/11/1.
//  Copyright © 2015年 baidu. All rights reserved.
//

import UIKit

 /// 在类的外面写的常量或者变量就是全局能够访问的

 /// 视图控制器切换通知字符串
let LNRootViewControllerSwitchNotification = "LNRootViewControllerSwitchNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
//        注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchViewController:", name: LNRootViewControllerSwitchNotification, object: nil)
        
        print(UserAccount.sharedAccount)
        setUpAppearance()
        
        print(isNewUpdate())
        
        // Override point for customization after application launch.
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultViewController()
        window?.makeKeyAndVisible()
        return true
    }
    
    deinit {
    
//        注销通知 - 只是一个习惯
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    /// 切换控制器, 记住：一定在AppDelegate中统一修改
    func switchViewController(n:NSNotification) {
        
        print("切换控制器 \(n)")
        let mainVC = n.object as? Bool
        
        window?.rootViewController == mainVC ? MainViewController() : WelcomeViewController()
        
        
         
    }
    
    
    private func defaultViewController() -> UIViewController {
        
//        1.判断用户是否登录，如果没有登录返回主控制器
        if !UserAccount.userLogon {
            
            return MainViewController()
        }
        
//        2. 判断是否是新版本，如果是，返回新特新，否则返回欢迎
        return isNewUpdate() ? NewFeatureViewController() : WelcomeViewController()
    }
    
    
    private func isNewUpdate() -> Bool {
        
//        1.获取程序当前的版本
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary! ["CFBundleShortVersionString"] as! String)!
//        2.获取程序'之前'的版本，偏好设置
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
//        3.将当前版本保存到偏好设置
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
//        ios 7.0之后，就不需要同步了，iOS 6.0之前，如果不同步不会第一时间写入沙盒
        NSUserDefaults.standardUserDefaults().synchronize()
//        4.返回比较结果
        return currentVersion > sandboxVersion
    }
    
    

//    设置外观
    private func setUpAppearance() {
    
//        一经设置，全局有效，应该尽早设置
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
   

}




















